//
//  SelfInformationViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/23.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "SelfInformationViewController.h"
#import "SelfInfoImageTableViewCell.h"
#import "SelfInfoLabelTableViewCell.h"
#import "SelfModifyNicknameViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <Foundation/Foundation.h>

static NSString *ImageCellID = @"ImageCellID";
static NSString *LabelCellID = @"InfoLabelCellID";
@interface SelfInformationViewController ()<UITableViewDelegate,UITableViewDataSource,SelfInfoImageTableCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate>

@property (nonatomic,strong)UIImagePickerController *imagePickerController;

@end

@implementation SelfInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.dataList addObject:[NSMutableArray arrayWithArray:@[@{@"key":@"头像",@"value":self.imgUrl?:@"selfCenter_HeaderImg"},@{@"key":@"昵称",@"value":self.nickname?:@""}]]];
    [self.dataList addObject:[NSMutableArray arrayWithArray:@[@{@"key":@"手机号",@"value":self.phone?:@""}]]];
    
    [self.tableView registerClass:[SelfInfoImageTableViewCell class] forCellReuseIdentifier:ImageCellID];
    [self.tableView registerClass:[SelfInfoLabelTableViewCell class] forCellReuseIdentifier:LabelCellID];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.dataList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [(NSMutableArray *)self.dataList[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        SelfInfoImageTableViewCell *imgCell = [self.tableView dequeueReusableCellWithIdentifier:ImageCellID];
        [imgCell cellForLayout:self.dataList[indexPath.section][indexPath.row]];
        imgCell.delegate = self;
        return imgCell;
    } else{
        SelfInfoLabelTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:LabelCellID];
        [cell cellForLayout:self.dataList[indexPath.section][indexPath.row]];
        return cell;
    }
}

- (void)infoImageTableCellTapAction{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    }else{
        AutoWeakSelf
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"修改用户头像" preferredStyle:UIAlertControllerStyleActionSheet];
        [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                weakSelf.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [weakSelf presentViewController:weakSelf.imagePickerController animated:YES completion:nil];
            }
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                weakSelf.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [weakSelf presentViewController:weakSelf.imagePickerController animated:YES completion:nil];
            }else{
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
                [alert show];
            }
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //发协议
    [self showLoadingTitle:@"正在上传头像"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kServiceID,kUploadUserImage];
    AutoWeakSelf
    [[QYNetManager sharedManager]upLoadSingeImage:urlStr parameters:nil andImage:image andImageName:currentTimeString SuccessBlock:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
             weakSelf.imgUrl = responseObject[@"data"];
            [weakSelf uploadImage];
        }else{
            [weakSelf showTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)uploadImage{
    NSDictionary * dict = @{@"member_id":K_UserDefault_Read(CustomerUserID)?:@"",
                            @"member_token":K_UserDefault_Read(CustomerUserToken)?:@"",
                            @"member_real_name":@"",
                            @"member_img":self.imgUrl?:@"",
                            @"member_nick_name":self.nickname,
                            @"member_birthday":@"",
                            @"member_sex":@""};
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kUpdateMemberDetail parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] integerValue]) {
                [weakSelf showTipWithTitle:@"修改成功"];
                [weakSelf.dataList replaceObjectAtIndex:0 withObject:@[@{@"key":@"头像",@"value":weakSelf.imgUrl?:@"selfCenter_HeaderImg"},@{@"key":@"昵称",@"value":weakSelf.nickname?:@""}]];
                [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [weakSelf showErrorTipWithTitle:@"修改失败\n请重试"];
            }
        }else{
            [weakSelf showTipWithTitle:responseObject[@"error"]];
        }
        
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 70;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 2.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 2)];
    backView.backgroundColor = [UIColor appColor];
    return backView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 2.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 2)];
    backView.backgroundColor = [UIColor appColor];
    return backView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 1) {
        SelfModifyNicknameViewController *nickVC = [SelfModifyNicknameViewController new];
        nickVC.nickname = self.nickname;
        nickVC.imgUrl = self.imgUrl?:@"";
        AutoWeakSelf
        nickVC.nickNameBlock = ^(NSString * _Nonnull nickname,NSString * _Nonnull imageUrl) {
            weakSelf.nickname = nickname;
            weakSelf.imgUrl = imageUrl;
            [weakSelf.dataList replaceObjectAtIndex:0 withObject:@[@{@"key":@"头像",@"value":imageUrl?:@"selfCenter_HeaderImg"},@{@"key":@"昵称",@"value":self.nickname?:@""}]];
            [weakSelf.tableView reloadData];
        };
        TAB_PUSH(self, nickVC, YES);
    }
}

- (UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
